<template>
  <el-form :model="formData" ref="formData" :rules="formRules" label-position="top" class="form-data">
    <el-form-item label="热门城市" prop="addressId" class="form-item-css">
      <el-cascader v-model="formData.addressId" ref="cascader" :props="props" @change="handleChange"
                   style="width: 100%" :key="formData.id"/>
    </el-form-item>
    <el-form-item class="form-button" v-if="!entity">
      <el-button class="but-view" @click="drawerClose">取 消</el-button>
      <el-button class="but-view" type="primary" @click="onSubmit">提 交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import {getProvinces} from '@/utils/common.js'
  export default {
    name: 'HotCityForm',
    props: {
      entity: Object
    },
    data() {
      return {
        formData: {
          addressId: null,
          name: null,
          id: null,
          parentId: null
        },
        formRules: {
          addressId: [
            { required: true, message: '请选择热门城市', trigger: 'change' }
          ]
        },
        props: getProvinces(1)
      }
    },
    beforeMount() {
      if (this.entity) this.getDetails()
    },
    methods: {
      /**
       * 省市区变化事件
       */
      handleChange(row) {
        const entity = this.$refs.cascader.getCheckedNodes()[0]
        const list = entity && entity.pathLabels && entity.pathLabels.length > 0 ? entity.pathLabels : [null, null, null]
        let arr = ['province', 'name']
        for (let i = 0; i < list.length; i++) this.formData[arr[i]] = list[i]
      },
      drawerClose() {
        this.$emit('close')
      },
      async onSubmit() {
        this.$refs.formData.validate(async(valid) => {
          if (!valid) return
          const formData = JSON.parse(JSON.stringify(this.formData))
          const [parentId, id] = JSON.parse(JSON.stringify(formData.addressId))
          formData.parentId =parentId
          formData.id = id
          formData.addressId = formData.addressId.join(',')
          await this.$ajax.post('/wx/cities/add', formData)
          this.$message.success('操作成功!')
          this.$emit('refresh')
          this.drawerClose()
        })
      },
      /**
       * 获取详情
       */
      async getDetails() {
        const res = await this.$ajax.get(`/wx/cities/info?id=${this.entity.id || ''}`)
        this.formData = res.data
      }
    }
  }
</script>

<style scoped>

</style>
